<?php
/**
 * 1.lumesse系统中新增部门信息同步到hroa.lumesse表,如没有对应员工,user_id置为0,需要确认的是这个部门的上下级部门关系 ，目前都是2级部门关系
 * 2.如果lumesse部门被删除,需要删除hroa.lumesse表的对应的信息
 * 3.lumesse系统中新增部门人员时，同步信息到hroa.lumesse表,对应好部门id
 * 4.人员在lumesse中变更了部门，也需要同步，如果是员工离职，判断状态后不需要再次同步到lumesse表
 *
 * Functional manager>Standard Recruiter
 * Hiring manager MSS Standard Hiring Manager
 */
apf_require_class('Oa_Job_Abstract');
apf_require_class("Bll_Flow_Lumesse");
class Oa_Job_Flow_SyncLumesseUser extends Oa_Job_Abstract {
    private $write_db = "hroa_master";//写数据库
    public function run() {
        $this->log("开始同步Lumesse用户信息".date('Y-m-d H:i:s'));

        $old_users = $this->_get_users_old();
        $new_users = $this->_get_users_lum();

        $new_users = $this->_execute_users($new_users,$old_users);

        $new_users = $this->_build_users($new_users);

        $this->_execute_database($new_users);//数据处理

        if($this->error_item){
            foreach($this->error_item as $error){
                $this->log("同步失败员工：".join(',',$error));
            }
        }
        $this->log("同步Lumesse用户信息处理完".date('Y-m-d H:i:s'));
    }
    private function logs($users,$name){
        ob_start();
        print_r($users);
        $con = ob_get_contents();
        file_put_contents('/tmp/'.$name, $con);
        ob_end_clean();
        exit;
    }
    /**
     * 构建数据
     */
    private function _build_users($users){
        //补全用户信息
        if(isset($users['add']) && !empty($users['add'])){
            foreach($users['add'] as $index=>$user){
                $temp_user = $this->_get_user_info_user_email($user['user_email'],$user['user_name']);
                if(!empty($temp_user)){
                    $user['hroa_depart_id'] = $temp_user['hroa_depart_id'];
                    $user['user_id'] = $temp_user['user_id'];
                    $users['add'][$index] = $user;
                }else{
                    unset($users['add'][$index]);
                }
            }
        }
        //检查部门变动,检查用户就职状态
        if(isset($users['edit']) && !empty($users['edit'])){
            //hroa变动
            foreach($users['edit'] as $index=>$user){
                $temp_user = $this->_get_user_info_user_id($user['user_id']);
                if(!empty($temp_user)){
                    $user['hroa_depart_id'] = $temp_user['hroa_depart_id'];
                    $users['edit'][$index] = $user;
                }else{
                    $users['delete'][] = $users['edit'][$index];
                    unset($users['edit'][$index]);
                }
            }
            //lums变动
            $tmp_user = array();
            foreach($users['edit'] as $index=>$user){
                $tmp_user[$user['user_id']][$index] = $user;
            }
            foreach($tmp_user as $tmp){
                $lums_user_id = 0;
                foreach($tmp as $t){
                    if($t['lums_user_id']){
                        $lums_user_id = $t['lums_user_id'];
                    }
                }
                $lums_departs = $this->_get_lumesse_user_info($lums_user_id);
                $num_old = count($tmp);
                $num_new = count($lums_departs);
                if($num_new == $num_old){
                    $key=0;
                    foreach($tmp as $index=>$t){
                        $users['edit'][$index]['lums_depart_ename'] = $lums_departs[$key]['lums_depart_ename'];
                        $users['edit'][$index]['lums_depart_name'] = $lums_departs[$key]['lums_depart_name'];
                        $users['edit'][$index]['lums_depart_id'] = $lums_departs[$key]['lums_depart_id'];
                        $users['edit'][$index]['lums_pdepart_ename'] = $lums_departs[$key]['lums_pdepart_ename'];
                        $users['edit'][$index]['lums_pdepart_name'] = $lums_departs[$key]['lums_pdepart_name'];
                        $users['edit'][$index]['lums_pdepart_id'] = $lums_departs[$key]['lums_pdepart_id'];
                        $key++;
                    }
                }elseif($num_new > $num_old){
                    $key=0;
                    $u = array();
                    foreach($tmp as $index=>$t){
                            $users['edit'][$index]['lums_depart_ename'] = $lums_departs[$key]['lums_depart_ename'];
                            $users['edit'][$index]['lums_depart_name'] = $lums_departs[$key]['lums_depart_name'];
                            $users['edit'][$index]['lums_depart_id'] = $lums_departs[$key]['lums_depart_id'];
                            $users['edit'][$index]['lums_pdepart_ename'] = $lums_departs[$key]['lums_pdepart_ename'];
                            $users['edit'][$index]['lums_pdepart_name'] = $lums_departs[$key]['lums_pdepart_name'];
                            $users['edit'][$index]['lums_pdepart_id'] = $lums_departs[$key]['lums_pdepart_id'];
                            $key++;
                            $u = $t;
                    }
                    for(;$key<$num_new;$key++){
                        $u['lums_depart_ename'] = $lums_departs[$key]['lums_depart_ename'];
                        $u['lums_depart_name'] = $lums_departs[$key]['lums_depart_name'];
                        $u['lums_depart_id'] = $lums_departs[$key]['lums_depart_id'];
                        $u['lums_pdepart_ename'] = $lums_departs[$key]['lums_pdepart_ename'];
                        $u['lums_pdepart_name'] = $lums_departs[$key]['lums_pdepart_name'];
                        $u['lums_pdepart_id'] = $lums_departs[$key]['lums_pdepart_id'];
                        $users['add'][] = $u;
                    }
                }elseif($num_new < $num_old){
                    $key=0;
                    foreach($tmp as $index=>$t){
                        if($key < $num_new){
                            $users['edit'][$index]['lums_depart_ename'] = $lums_departs[$key]['lums_depart_ename'];
                            $users['edit'][$index]['lums_depart_name'] = $lums_departs[$key]['lums_depart_name'];
                            $users['edit'][$index]['lums_depart_id'] = $lums_departs[$key]['lums_depart_id'];
                            $users['edit'][$index]['lums_pdepart_ename'] = $lums_departs[$key]['lums_pdepart_ename'];
                            $users['edit'][$index]['lums_pdepart_name'] = $lums_departs[$key]['lums_pdepart_name'];
                            $users['edit'][$index]['lums_pdepart_id'] = $lums_departs[$key]['lums_pdepart_id'];
                            $key++;
                        }else{
                            unset($users['edit'][$index]);
                            $users['delete'][] = $t;
                        }
                    }
                }
            }
        }
        return $users;
    }
    /**
     * 数据库处理
     */
    private function _execute_database($new_users){

        if(isset($new_users['add']) && !empty($new_users['add'])){
            foreach($new_users['add'] as $user){
                $this->_add_user_info($user);
            }
        }
        if(isset($new_users['edit']) && !empty($new_users['edit'])){
            foreach($new_users['edit'] as $user){
                $this->_update_user_info($user);
            }
        }
        if(isset($new_users['delete']) && !empty($new_users['delete'])){
            foreach($new_users['delete'] as $user){
                $this->_delete_user_info($user['id']);
            }
        }
    }
    private function _execute_users($new_users,$old_users){
        $result = array();
        $old_users = $this->_build_key_value_lums("lums_user_id",$old_users);
        $old_users_lumids = array_keys($old_users);
        $new_users_lumids = array();
        foreach ($new_users as $user){
            if(in_array($user->id, $old_users_lumids)){
                foreach($old_users[$user->id] as $ol_u){
                    $ol_u['lums_account'] = $user->login;
                    $result['edit'][] = $ol_u;
                }
            }else{
                $tmp = array(
                        'lums_account'=>$user->login,
                        'lums_user_id'=>$user->id,
                        'user_email'  =>$user->email,
                        'user_name'   =>$user->lastName.''.$user->firstName
                );
                $departs = $this->_get_lumesse_user_info($user->id);
                foreach($departs as $depart){
                    $result['add'][] = array_merge($depart,$tmp);
                }
            }
            $new_users_lumids[] = $user->id;
        }
        foreach ($old_users as $lums_user_id=>$user){
            if(!in_array($lums_user_id, $new_users_lumids)){
                foreach($user as $one){
                    $result['delete'][] = $one;
                }
            }
        }
        return $result;
    }
    private function _get_lumesse_user_info($lum_user_id){
        if(!$lum_user_id){
            return array();
        }
        if(!$this->_lums_user_info || !isset($this->_lums_user_info[$lum_user_id])){
            $recruiters = array('Standard Recruiter','Functional Manager','Hiring Manager MSS','Standard Hiring Manager');
            $result = array();
            $lumesse_user_user = $this->_get_lumesse_user_soap();
            $rolers = $lumesse_user_user->getRolesAssignedForUser(array('userId'=>$lum_user_id));

            $index = 0;
            foreach($rolers->userRoleAssignment as $role){
                if(in_array($role->role->name, $recruiters)){
                    if($role->organization && $role->organization->unit){
                        $unit = $role->organization->unit;
                        if(isset($unit->code) && $unit->code){
                            if( $unit->level==1 ){
                                $tmp = array(
                                            'lums_depart_id'=>$unit->id,
                                            'lums_depart_ename'=>$unit->code,
                                            'lums_depart_name'=>$unit->_,
                                            'lums_pdepart_id'=>0,
                                            'lums_pdepart_ename'=>'',
                                            'lums_pdepart_name'=>''
                                            );
                                if($tmp && !$this->_check_eq($result,$tmp)){
                                    $result[$index] = $tmp;
                                    $index++;
                                }
                            }
                        }else{
                            $tmp = array();
                            foreach($unit as $u){
                                    $tmp['lums_pdepart_id']=0;
                                    $tmp['lums_pdepart_ename']='';
                                    $tmp['lums_pdepart_name']='';
                                    $tmp['lums_depart_id']=$u->id;
                                    $tmp['lums_depart_ename']=$u->code;
                                    $tmp['lums_depart_name']=$u->_;
                            }
                            if($tmp && !$this->_check_eq($result,$tmp)){
                                $result[$index] = $tmp;
                                $index++;
                            }
                        }
                    }
                }
            }
            $this->_lums_user_info[$lum_user_id] = $result;
        }
        return $this->_lums_user_info[$lum_user_id];
    }
    /**
     * 检测相同
     * @param array $data
     * @param object $unit
     * @return boolean
     */
    private function _check_eq($data,$unit){
        $bool = false;
        foreach($data as $one){
            if($one['lums_depart_id'] == $unit['lums_depart_id'] && $one['lums_depart_ename'] == $unit['lums_depart_ename']
                    && $one['lums_depart_name'] == $unit['lums_depart_name'] && $one['lums_pdepart_name'] == $unit['lums_pdepart_name']
                    && $one['lums_pdepart_id'] == $unit['lums_pdepart_id'] && $one['lums_pdepart_ename'] == $unit['lums_pdepart_ename'] ){
                $bool = true;
            }
        }
        return $bool;
    }
    /**
     * 修改用户信息
     */
    private function _update_user_info($data){
        if(empty($data['hroa_depart_id'])){
            return false;
        }
        $sql = "UPDATE lumesse SET ";
        $sql.="lums_depart_ename='".str_replace("'", "''", $data['lums_depart_ename'])."',";
        $sql.="lums_depart_name='".str_replace("'", "''", $data['lums_depart_name'])."',";
        $sql.="lums_depart_id=".$data['lums_depart_id'].",";
        $sql.="lums_pdepart_ename='".$data['lums_pdepart_ename']."',";
        $sql.="lums_pdepart_name='".$data['lums_pdepart_name']."',";
        $sql.="lums_pdepart_id=".$data['lums_pdepart_id'].",";
        $sql.="hroa_depart_id=".$data['hroa_depart_id'].",";
        $sql.="lums_account='".$data['lums_account']."',";
        $sql.="lums_user_id=".$data['lums_user_id']."";
        $sql.=" WHERE id=".$data['id'];
        $this->execute( $sql,array(), $this->write_db);
    }
    /**
     * 删除用户信息
     */
    private function _delete_user_info($id){
        $sql = "DELETE FROM lumesse WHERE id =".$id;
        $this->execute($sql,array(),$this->write_db);
    }
    /**
     * 所有hroa中lumesse表中用户
     */
    private function _get_users_old(){
        $sql = "SELECT * from lumesse ";
        return $this->get_db_rows($sql,$this->write_db,array());
    }
    /**
     * 构建key-alue
     */
    private function _build_key_value_lums($key,$data){
        $result = array();
        foreach($data as $one){
            $result[$one[$key]][] = $one;
        }
        return $result;
    }
    private function _build_key_value($key,$data){
        $result = array();
        foreach($data as $one){
            $result[$one[$key]] = $one;
        }
        return $result;
    }
    /**
     * 所有lumesse系统用户
     */
    private function _get_users_lum(){
        $lumesse_user_user = $this->_get_lumesse_user_soap();
        $users = $lumesse_user_user->getUsers();
        return $users->user;
    }
    private function _get_lumesse_user_soap(){
        if(!$this->lumesse_user_user){
            $this->lumesse_user_user = Bll_Flow_Lumesse::get_instance()->Lumesse_User()->User();
        }
        return $this->lumesse_user_user;
    }
    /**
     * 获取用户id,和部门id
     */
    private function _get_user_info_user_email($user_email,$user_name){
        if(!$this->_user_info_email || !isset($this->_user_info_email[$user_email])){
            $user_email = trim($user_email);
            $sql = "SELECT user_id FROM user WHERE job_status=1 AND office_mail='".$user_email."'";
            $user = $this->get_db_row($sql,$this->write_db);
            if(isset($user['user_id']) && $user_email){
                $sql = "SELECT job_id FROM work WHERE user_id=".$user['user_id']." AND is_parttime=1 AND is_deleted=1";
                $work = $this->get_db_row($sql,$this->write_db);
                $sql = "SELECT department_id FROM job WHERE job_id=".$work['job_id']." AND is_deleted=1";
                $job  = $this->get_db_row($sql,$this->write_db);
                $this->_user_info_email[$user_email] = array('user_id'=>$user['user_id'],'hroa_depart_id'=>$job['department_id']);
            }else{
                $this->error_item[] = array($user_name,$user_email);
                $this->_user_info_email[$user_email] = array();
            }
        }
        return $this->_user_info_email[$user_email];

    }
    private function _get_user_info_user_id($user_id){
        if(!$this->_user_info || !isset($this->_user_info[$user_id])){
            $sql = "SELECT job_id FROM work WHERE user_id=".$user_id." AND is_parttime=1 AND is_deleted=1";
            $work = $this->get_db_row($sql,$this->write_db);
            $sql = "SELECT department_id FROM job WHERE job_id=".$work['job_id']." AND is_deleted=1";
            $job  = $this->get_db_row($sql,$this->write_db);
            $this->_user_info[$user_id] = array('user_id'=>$user_id,'hroa_depart_id'=>$job['department_id']);
        }
        return $this->_user_info[$user_id];
    }
    /**
     * 写入数据
     */
    private function _add_user_info($data){
        $sql = "INSERT INTO lumesse(user_id,lums_depart_ename,lums_depart_name,lums_depart_id,lums_pdepart_ename,lums_pdepart_name,lums_pdepart_id,user_name,user_email,hroa_depart_id,lums_account,lums_user_id) VALUES(";
        $sql.="".$data['user_id'].',';
        $sql.="'".str_replace("'", "''", $data['lums_depart_ename'])."',";
        $sql.="'".str_replace("'", "''", $data['lums_depart_name'])."',";
        $sql.="".$data['lums_depart_id'].",";
        $sql.="'".$data['lums_pdepart_ename']."',";
        $sql.="'".$data['lums_pdepart_name']."',";
        $sql.="".$data['lums_pdepart_id'].",";
        $sql.="'".$data['user_name']."',";
        $sql.="'".$data['user_email']."',";
        $sql.="".$data['hroa_depart_id'].",";
        $sql.="'".$data['lums_account']."',";
        $sql.="".$data['lums_user_id']."";
        $sql.=")";
        file_put_contents('/tmp/lumesse_sql', $sql,FILE_APPEND);
        $this->execute( $sql,array(), $this->write_db);
    }
}